import os
import requests
import hashlib
import json

# 写入路径
CACHE_DIR = "/workspace/comfyui/ComfyUI/custom_nodes/comfyui-manager/.cache"
os.makedirs(CACHE_DIR, exist_ok=True)

# 目标 URI 列表（默认 ComfyUI-Manager 拉取的）
URIS = [
    "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/alter-list.json",
    "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/model-list.json",
    "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/github-stats.json",
    "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/extension-node-map.json",
    "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/custom-node-list.json",
    "https://api.comfy.org/nodes"
]

def simple_hash(s):
    h = 0
    for c in s:
        h = (h * 31 + ord(c)) % (2**32)
    return str(h)

def sanitize_filename(s):
    return s.replace("&", "_").replace("?", "_").replace("=", "_")

for uri in URIS:
    try:
        print(f"正在下载：{uri}")
        resp = requests.get(uri, timeout=10)
        resp.raise_for_status()

        cache_name = f"{simple_hash(uri)}_{sanitize_filename(os.path.basename(uri))}.json"
        path = os.path.join(CACHE_DIR, cache_name)
        with open(path, "w", encoding="utf-8") as f:
            json.dump(resp.json(), f, indent=4)

        print(f"✅ 缓存已保存：{path}")

    except Exception as e:
        print(f"❌ 下载失败：{uri}，错误：{e}")
